<template>
  <!-- 选择纠正措施:针对流出根本原因表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="1000"
    draggable
    @close="closeDialog"
    destroy-on-close
    :append-to-body="true"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="0">
      <el-row>
        <el-col :span="24">
          <span style="font-weight: 700"
            >纠正措施：执行了什么测试/试验/过程来确认纠正措施可以防止缺陷再次发生?</span
          >
          <el-form-item prop="exceptionContent">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.exceptionContent"
              type="textarea"
              :rows="8"
              placeholder="请输入"
              clearable
            />
            <div v-else>{{ formData.exceptionContent }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="负责人" prop="superintendent" label-width="80">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.superintendent"
              placeholder="请输入负责人"
              style="width: 200px"
              clearable
            />

            <span v-else>{{ formData.superintendent }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="完成时间"
            prop="planDate"
            label-width="100"
            style="float: right"
          >
            <el-date-picker
              v-if="!props.isReadonly"
              v-model="formData.planDate"
              type="date"
              style="width: 200px"
              placeholder="完成时间"
            />

            <span v-else>{{ formData.planDate?.split(" ")[0] }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <el-form-item
        style="margin-top: 10px"
        v-if="!props.isReadonly && loading1"
      >
        <CommonUploadFile
          :isRead="props.isReadonly"
          :files="formData.assetPhotos"
          @update-files="updateFormFiles"
        />
      </el-form-item>
    </el-row>
    <div
      style="margin-top: 0px"
      v-if="loading1 && formData.assetPhotos.length > 0"
    >
      <CommonUploadFile
        v-show="props.isReadonly"
        :isRead="props.isReadonly"
        :files="formData.assetPhotos"
        @update-files="updateFormFiles"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="success"
          :loading="loading"
          @click="handleSubmit(1)"
          >提 交</el-button
        >
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit(0)"
          >保 存</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSQ8DD52ADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (!props.data?.id) {
      loading1.value = true;
    }
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  exceptionContent: [
    { required: true, message: "请输入", trigger: "blur" },
    { min: 1, max: 1000, message: "长度在 1 到 1000 个字符", trigger: "blur" },
  ],
  superintendent: [
    { required: true, message: "请输入责任人", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  planDate: [{ required: true, message: "请输入完成时间", trigger: "blur" }],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  qualityExceptionId: "",
  qualityExceptionCode: "",
  exceptionContent: "",
  superintendent: "",
  planDate: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  assetPhotos: [],
  isSubmit: 0,
  workOrderId: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        qualityExceptionId,
        qualityExceptionCode,
        exceptionContent,
        superintendent,
        planDate,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        assetPhotos,
      } = newVal;
      Object.assign(formData, {
        id,
        qualityExceptionId,
        qualityExceptionCode,
        exceptionContent,
        superintendent,
        planDate,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        assetPhotos: assetPhotos ?? [],
      });
      formData.qualityExceptionId = newVal.qualityProblemId;
      formData.qualityExceptionCode = newVal.qualityProblemCode;
      formData.workOrderId = newVal.id;
      loading1.value = false;
      getD52(newVal.id);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.qualityExceptionId = "";
  formData.qualityExceptionCode = "";
  formData.exceptionContent = "";
  formData.superintendent = "";
  formData.planDate = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.assetPhotos = [];
  formData.isSubmit = 0;
  formData.workOrderId = "";
}

const loading = ref(false);
const loading1 = ref(false);
/** 选择纠正措施:针对流出根本原因保存提交 */
function handleSubmit(state: Number) {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = state == 0 ? "保存" : "提交";
      formData.isSubmit = state;
      await request({
        url: "/qms/q8dd52/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
// 图片处理
function updateFormFiles(val: []) {
  formData.assetPhotos = val;
}
//获取业务信息D71
const hh = ref(false);
const getD52 = async (id: string) => {
  if (id) {
    console.log("ids", id);
    await request({
      url: "/qms/q8dd52/getD52",
      method: "post",
      data: {
        qualityExceptionId: id,
      },
    })
      .then((res) => {
        if (res.data != null) {
          Object.assign(formData, res.data);
          loading1.value = true;
        } else {
          formData.id = "";
          loading1.value = true;
        }
      })
      .finally(() => {
        loading1.value = true;
      });
  } else {
    loading1.value = true;
  }
};
</script>
